package com.photoeditor.demo.model.face.report.reportlogic;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.support.v7.widget.AppCompatTextView;
import android.support.v8.renderscript.Allocation;
import android.support.v8.renderscript.Element;
import android.support.v8.renderscript.RenderScript;
import android.support.v8.renderscript.ScriptIntrinsicBlur;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import androidx.annotation.RequiresApi;

import com.airbnb.lottie.LottieAnimationView;
import com.common.base.ComponentContext;
import com.common.base.log.DLog;
import com.common.base.utils.DeviceUtils;
import com.common.base.utils.thread.ThreadPool;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.base.Request;
import com.photoeditor.R;
import com.photoeditor.demo.imageloader.ImageLoader;
import com.photoeditor.demo.model.bean.BabyInputBean;
import com.photoeditor.demo.model.bean.face.BabyPredicResultBean;
import com.photoeditor.demo.model.bean.face.FaceDetectBeanV4;
import com.photoeditor.demo.model.event.GotoAdVideoPageEvent;
import com.photoeditor.demo.model.event.GotoSubscribePageEvent;
import com.photoeditor.demo.model.event.VipMaskIsShowEvent;
import com.photoeditor.demo.model.face.FaceConstant;
import com.photoeditor.demo.model.image.util.ImageHelper;
import com.photoeditor.demo.model.preference.SPDataManager;
import com.photoeditor.demo.model.preference.SpUtils;
import com.photoeditor.demo.model.subscribe.manager.AppVipManager;
import com.photoeditor.demo.statistics.StatisticsConstant;
import com.photoeditor.demo.statistics.StatisticsUtils;
import com.photoeditor.demo.ui.activity.face.FaceLogicActivity;
import com.photoeditor.demo.util.APKAssertImageLoader;
import com.photoeditor.demo.util.BitmapUtils;
import com.photoeditor.demo.util.BlurUtil;
import com.photoeditor.demo.util.FastBlur;
import com.photoeditor.demo.util.JsonCallback;
import com.photoeditor.demo.util.SignUtils;
import com.photoeditor.demo.util.TimeConstant;
import com.photoeditor.demo.util.ToastUtil;
import com.photoeditor.demo.util.face.FaceUtil;
import com.photoeditor.demo.util.transformation.BlurTransformation;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import static com.photoeditor.demo.model.bean.face.BaseFaceResultBean.REPORT_TYPE_BABYPREDICT;
import static com.photoeditor.demo.model.preference.SpUtils.EFFECT_NAME;
import static com.photoeditor.demo.statistics.StatisticsConstant.STATISTIC_EVENT_VALUE_FACE_AGING_PARKING_TIME_10;
import static com.photoeditor.demo.statistics.StatisticsConstant.STATISTIC_EVENT_VALUE_FACE_AGING_PARKING_TIME_4;
import static com.photoeditor.demo.statistics.StatisticsConstant.STATISTIC_EVENT_VALUE_FACE_AGING_PARKING_TIME_6;
import static com.photoeditor.demo.statistics.StatisticsConstant.STATISTIC_EVENT_VALUE_FACE_AGING_PARKING_TIME_ABOVE_10;
import static com.photoeditor.demo.util.measureTextViewSizeUtils.measureTextViewSize;

/**
 * Created by @author winn on 2018/10/30.
 */

public class FutureBabyReportLogic extends BaseReportLogic {

    private final String TAG = FutureBabyReportLogic.class.getSimpleName();

    private FaceDetectBeanV4 mResultBean;
    private ImageView mImgResult;
    private LottieAnimationView mLoadingView;

    private Context mContext;

    private View mGenderSwitchView;
    private View mContainerView;
    private View mMaskLayout;
    private ImageView mIvFather;
    private ImageView mIvMothoer;
    private ImageView mIvBack;
    private Button mBtnRetry;
    private Button mBtnSave;

    private boolean mIsLoading;
    private String mImagePath;
    private String mCompressPic;
    private String mResultBase64;
    private String mCurrentPath;
    private Bitmap mOriBitmap;
    private Bitmap mBluredUserBitmap;
    private Bitmap mBluredScreenBitmap;

    private String mPathFather;
    private String mPathMother;
    private BabyInputBean mBabyInputBean;

    private Activity mActivity;

    private boolean mIsModel;

    public FutureBabyReportLogic(String imagePathFather, String imagePathMother) {
        super(REPORT_TYPE_BABYPREDICT);
        mPathFather = imagePathFather;
        mPathMother = imagePathMother;
    }

    public void setActivity(Activity activity) {
        mActivity = activity;
    }

    public void setBabyInputBean(BabyInputBean bean) {
        mBabyInputBean = bean;
    }

    @Override
    public View getReportView(ViewGroup parent) {
        mContext = parent.getContext();
        ViewGroup viewGroup = (ViewGroup) LayoutInflater.from(parent.getContext())
                .inflate(R.layout.report_baby_prediction, parent, false);
        initView(viewGroup);

        updateViewIfNecessary();
        return viewGroup;
    }

    private void initView(View rootView) {
        mContentView = rootView;
        mImgResult = rootView.findViewById(R.id.iv_effect);
        mLoadingView = rootView.findViewById(R.id.loading_animation_view);
        mContainerView = rootView.findViewById(R.id.pic_container);
        mIvFather = rootView.findViewById(R.id.iv_father);
        mIvMothoer = rootView.findViewById(R.id.iv_mother);
        mIvBack = rootView.findViewById(R.id.iv_back);
        mBtnRetry = rootView.findViewById(R.id.btn_retry);
        mBtnSave = rootView.findViewById(R.id.btn_save);
        mBtnRetry.setOnClickListener(this);
        mBtnSave.setOnClickListener(this);
        mIvBack.setOnClickListener(this);

        ImageLoader.loadImage(mPathFather, mIvFather);
        ImageLoader.loadImage(mPathMother, mIvMothoer);
    }

    /**
     * 更新用户头像
     */
    private void updateViewIfNecessary() {
        updateUserView();
        checkVipView();
        checkModelRequest();
        makeRealRequest();
    }

    /**
     * model的假loading请求
     * 2s后展示结果
     */
    private void checkModelRequest() {
        if (!mIsModel) {
            return;
        }
        showLoading();
        ThreadPool.runUITask(new Runnable() {
            @Override
            public void run() {
                hideLoading();
                setDefaultModelView();
                if (mActivity != null && mActivity instanceof FaceLogicActivity) {
                    ((FaceLogicActivity) mActivity).fakeScanReqSucc();
                }
            }
        }, 2000);
    }

    private void makeRealRequest() {
        if (!AppVipManager.isVip()) {
            return;
        }
        requestBabyReport(mBabyInputBean);
    }

    private void setDefaultModelView() {
        if (mIsModel) {
            //设置头像
            String path = FaceConstant.getModleGengerFeMale(mImagePath);
            APKAssertImageLoader.with(mContext.getResources()).load(path).into(mImgResult);

        }
    }

    /**
     * 重置和用户图像相关的数据
     */
    private void resetData() {
        mIsModel = false;
        mResultBean = null;
        mResultBase64 = null;        //请求结果
        mCompressPic = null;         //缓存

        mBluredUserBitmap = null;
        mBluredScreenBitmap = null;
    }

    @Override
    public void updateImage(String image) {
        if (TextUtils.equals(mImagePath, image)) {
            return;
        }
        mImagePath = image;
        if (FaceConstant.isModel(mImagePath)) {
            if (mActivity != null && mActivity instanceof FaceLogicActivity) {
                ((FaceLogicActivity) mActivity).fakeScanReq();
            }
        }
        resetData();
        updateViewIfNecessary();
    }

    /**
     * 更新用户头像
     */
    private void updateUserView() {
        mIsModel = FaceConstant.isModel(mImagePath);

        if (mIsModel) {
            mOriBitmap = APKAssertImageLoader.with(mContext.getResources()).load(mImagePath).get();
        } else {
            mOriBitmap = BitmapFactory.decodeFile(mImagePath);
            if (mOriBitmap != null && FaceLogicActivity.degree != 0){  //旋转
                Matrix m = new Matrix();
                m.setRotate(FaceLogicActivity.degree, (float) mOriBitmap.getWidth() / 2, (float) mOriBitmap.getHeight() / 2);
                try {
                    mOriBitmap = Bitmap.createBitmap(mOriBitmap, 0, 0, mOriBitmap.getWidth(), mOriBitmap.getHeight(), m, true);
                } catch (OutOfMemoryError ex) {
                    //
                }
            }
        }
        mCurrentPath = mImagePath;
        if (!AppVipManager.isVip()) {
            mOriBitmap = BitmapFactory.decodeResource(mActivity.getResources(), R.drawable.ic_baby_model);
            mImgResult.setImageBitmap(mOriBitmap);
        }
    }

    public void setResultBean(FaceDetectBeanV4 resultBean) {
        mResultBean = resultBean;
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        switch (id) {
            case R.id.switch_image:
                if (mOnEventListener != null) {
                    mOnEventListener.switchImage();
                }
                break;
            case R.id.iv_back:
                if (mActivity != null) {
                    mActivity.onBackPressed();
                }
                break;
            case R.id.btn_retry:
                if (mActivity != null) {
                    ((FaceLogicActivity)mActivity).enterGallery();
                }
                break;
            case R.id.btn_save:
                if (mActivity != null) {
                    if (mActivity != null) {
                        if (AppVipManager.isVip()) {
                            ((FaceLogicActivity) mActivity).checkPermission();
                        } else {
                            ((FaceLogicActivity) mActivity).showSubscribeDialog(false);
                        }
                    }
                }
                break;
            default:
                super.onClick(view);
        }
    }

    @Override
    public void onSubscribeSuccess() {
        if (mMaskLayout != null) {
            mMaskLayout.setVisibility(View.GONE);
        }
        mOriBitmap = null;
        mImgResult.setImageBitmap(null);
        makeRealRequest();
    }

    private void checkVipView() {
        if (AppVipManager.isVip() || mIsModel) {
            if (mMaskLayout != null) {
                mMaskLayout.setVisibility(View.INVISIBLE);
            }
            return;
        }
        //非vip用户弹出遮罩
        if (mMaskLayout != null) {
            createBluredUserBitmap(mOriBitmap);                 //生成用户模糊图片
            mImgResult.setImageBitmap(mBluredUserBitmap);       //设置用户模糊图片
            ThreadPool.runUITask(new Runnable() {               //设置全屏非Vip遮罩
                @Override
                public void run() {
                    createBluredScreenBitmap();
                    if (mBluredScreenBitmap != null) {
//                        mMaskLayout.setBackground(new BitmapDrawable(mBluredScreenBitmap));
                        //applyBlur(mMaskLayout);
                        BlurUtil.applyBlur((Activity) mContext, mMaskLayout);
                    }
                }
            }, 100);
            mMaskLayout.setVisibility(View.VISIBLE);
            return;
        }
        ViewStub maskStub = (ViewStub) mContentView.findViewById(R.id.stub_subscribe_mask);
        StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_FUZZY_SHOW,
                StatisticsConstant.KEY_VIP_FUN, StatisticsConstant.VALUE_VIP_FUN_FUTURE_BABY,
                StatisticsConstant.KEY_FILTER_NAME,StatisticsConstant.VALUE_RATE_TIME_FUTURE_BABY);
        mMaskLayout = maskStub.inflate();
        AppCompatTextView textView=mMaskLayout.findViewById(R.id.btn_vip_confirm);
        measureTextViewSize(mActivity,textView,200);
        createBluredUserBitmap(mOriBitmap);             //生成用户模糊图片
        mImgResult.setImageBitmap(mBluredUserBitmap);   //设置用户模糊图片
        ThreadPool.runUITask(new Runnable() {           //设置全屏非Vip遮罩
            @Override
            public void run() {
                createBluredScreenBitmap();
                if (mBluredScreenBitmap != null) {
//                    mMaskLayout.setBackground(new BitmapDrawable(mBluredScreenBitmap));
//                    applyBlur(mMaskLayout);
                    BlurUtil.applyBlur((Activity) mContext, mMaskLayout);
                }
            }
        }, 100);

        if ((SPDataManager.getTodayHasShowedNorStickersSubscribeMaskCount() < 3)) {
            DLog.d("wLog", "前2次显示模糊页，则页面上不显示激励视频按钮，" +
                    "并在进入模糊页后自动跳转到主订阅页，从主订阅页返回到模糊页，并显示激励视频解锁按钮");
            RelativeLayout.LayoutParams lps = (RelativeLayout.LayoutParams) mMaskLayout.findViewById(R.id.rl_continue_vip).getLayoutParams();
            lps.bottomMargin = DeviceUtils.dip2px(24);
            mMaskLayout.findViewById(R.id.rl_continue_vip).setLayoutParams(lps);
            mMaskLayout.findViewById(R.id.rip_ll_watch_ad).setVisibility(View.GONE);
        }
        //策略平台控制，0——旧样式，1——AD弹框，2——评分引导一天免费弹框
//        RateNewStrategyBean.RateNewStrategyBeanConfig beanConfig = OneFreeStrategyManager.getOneFreeVipOrAdStrategyConfig();
//        boolean value = SPDataManager.getTodayHasShowedAllSubscribeMaskCount() == 2;
//        if (value) {
//            DLog.d("wLog", "第二次进入模糊页，隐藏watch ad按钮");
//        } else {
//            DLog.d("wLog", "第二次进入模糊页，应该展示watch ad按钮");
//        }
//        if (value || (SPDataManager.getTodayHasShowedAllSubscribeMaskCount() == 2) || SPDataManager.isFirstCloseSubsPage() || ((beanConfig == null || beanConfig.getRateType() != ADVANCE_OBTAIN_RESULT))) {
//            //模糊页不展示watch video按钮
//            RelativeLayout.LayoutParams lps = (RelativeLayout.LayoutParams) mMaskLayout.findViewById(R.id.rl_continue_vip).getLayoutParams();
//            lps.bottomMargin = DeviceUtils.dip2px(24);
//            mMaskLayout.findViewById(R.id.rl_continue_vip).setLayoutParams(lps);
//            mMaskLayout.findViewById(R.id.rip_ll_watch_ad).setVisibility(View.GONE);
//        } else {
//            DLog.d("wLog", "不隐藏watch ad按钮");
//        }
        mMaskLayout.findViewById(R.id.rl_continue_vip).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_FUZZY_BUTT_CLICK,
                        StatisticsConstant.KEY_VIP_FUN, StatisticsConstant.VALUE_VIP_FUN_FUTURE_BABY,
                        StatisticsConstant.KEY_FILTER_NAME,StatisticsConstant.VALUE_RATE_TIME_FUTURE_BABY);
                //跳转到订阅页面
                EventBus.getDefault().post(new GotoSubscribePageEvent());
            }
        });
        mMaskLayout.findViewById(R.id.rip_ll_watch_ad).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //跳转到激励视频
                StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_VIDEO_BUTTON_CLICK,
                        StatisticsConstant.KEY_SHOW_TYPE, StatisticsConstant.VALUE_BUTTON,
                        StatisticsConstant.KEY_VIP_FUN, StatisticsConstant.VALUE_VIP_FUN_FUTURE_BABY,
                        StatisticsConstant.KEY_FILTER_NAME,StatisticsConstant.VALUE_RATE_TIME_FUTURE_BABY);
                SpUtils.obtain().save(EFFECT_NAME, "baby");
                EventBus.getDefault().post(new GotoAdVideoPageEvent());
            }
        });

        if (mMaskLayout.findViewById(R.id.rip_ll_watch_ad).getVisibility() == View.VISIBLE){
            StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_VIDEO_BUTTON_SHOW,
                    StatisticsConstant.KEY_SHOW_TYPE, StatisticsConstant.VALUE_BUTTON,
                    StatisticsConstant.KEY_VIP_FUN, StatisticsConstant.VALUE_RATE_TIME_FUTURE_BABY,
                    StatisticsConstant.KEY_FILTER_NAME,StatisticsConstant.VALUE_RATE_TIME_FUTURE_BABY);
        }

        if (mMaskLayout.getVisibility() == View.VISIBLE) {
            ThreadPool.runUITask(new Runnable() {               //设置全屏非Vip遮罩
                @Override
                public void run() {
                    EventBus.getDefault().post(new VipMaskIsShowEvent());
                }
            }, 1000);
        }

    }

    private void createBluredScreenBitmap() {
        if (mMaskLayout != null) {
            View activityView = mContainerView;
            activityView.setDrawingCacheEnabled(true);
            activityView.destroyDrawingCache();
            activityView.buildDrawingCache();
            Bitmap bmp = activityView.getDrawingCache();
            if (bmp != null) {
                Bitmap copy = bmp.copy(Bitmap.Config.ARGB_8888, true);
                BlurUtil.blur(ComponentContext.getContext(), copy, 10);
                BlurUtil.drawDarkCover(copy);
                mBluredScreenBitmap = copy;
            }
            activityView.destroyDrawingCache();
            activityView.setDrawingCacheEnabled(false);
        }
    }

    private void createBluredUserBitmap(Bitmap srcBitmap) {
        int scaleRatio = 5;
        if (srcBitmap == null || srcBitmap.isRecycled()) {
            return;
        }
        Bitmap blurBitmap = srcBitmap.createScaledBitmap(srcBitmap,
                srcBitmap.getWidth() / scaleRatio,
                srcBitmap.getHeight() / scaleRatio,
                false);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
            blurBitmap = BlurTransformation.blur(ComponentContext.getContext(), blurBitmap, 5);
        } else {
            blurBitmap = FastBlur.doBlur(blurBitmap, 5, true);
        }
        Paint bitmapPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG);
        mBluredUserBitmap = Bitmap.createBitmap(blurBitmap.getWidth(), blurBitmap.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas1 = new Canvas(mBluredUserBitmap);
        canvas1.drawBitmap(blurBitmap, 0, 0, bitmapPaint);
    }

    /**
     * 首次订阅页返回时调用
     */
    public void updateMaskLayout() {
        if (AppVipManager.isVip()) {
            return;
        }
        if (mMaskLayout != null) {
            checkVipView();
            RelativeLayout.LayoutParams lps = (RelativeLayout.LayoutParams) mMaskLayout.findViewById(R.id.rl_continue_vip).getLayoutParams();
            lps.bottomMargin = DeviceUtils.dip2px(0);
            mMaskLayout.findViewById(R.id.rl_continue_vip).setLayoutParams(lps);
            mMaskLayout.findViewById(R.id.rip_ll_watch_ad).setVisibility(View.VISIBLE);
            if (mMaskLayout.findViewById(R.id.rip_ll_watch_ad).getVisibility() == View.VISIBLE){
                StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_VIDEO_BUTTON_SHOW,
                        StatisticsConstant.KEY_SHOW_TYPE, StatisticsConstant.VALUE_BUTTON,
                        StatisticsConstant.KEY_VIP_FUN, StatisticsConstant.VALUE_RATE_TIME_FUTURE_BABY,
                        StatisticsConstant.KEY_FILTER_NAME,StatisticsConstant.VALUE_RATE_TIME_FUTURE_BABY);
            }
//            StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_VIDEO_BUTTON_SHOW,
//                        StatisticsConstant.KEY_SHOW_TYPE, StatisticsConstant.VALUE_BUTTON,
//                        StatisticsConstant.KEY_VIP_FUN, StatisticsConstant.VALUE_RATE_TIME_GENDER_SWAP);
//            RateNewStrategyBean.RateNewStrategyBeanConfig beanConfig = OneFreeStrategyManager.getOneFreeVipOrAdStrategyConfig();
//            boolean value = SPDataManager.getTodayHasShowedAllSubscribeMaskCount() != 2;
//            if (value) {
//                DLog.d("wLog", "非第二次进入模糊页，应该展示watch ad按钮, extra: " + ((beanConfig != null && beanConfig.getRateType() == ADVANCE_OBTAIN_RESULT)));
//            } else {
//                DLog.d("wLog", "非第二次进入模糊页，不应该显示watch ad按钮, extra: " + ((beanConfig != null && beanConfig.getRateType() == ADVANCE_OBTAIN_RESULT)));
//            }
//            if (value && (beanConfig != null && beanConfig.getRateType() == ADVANCE_OBTAIN_RESULT)) {
//                RelativeLayout.LayoutParams lps = (RelativeLayout.LayoutParams) mMaskLayout.findViewById(R.id.rl_continue_vip).getLayoutParams();
//                lps.bottomMargin = DeviceUtils.dip2px(0);
//                mMaskLayout.findViewById(R.id.rl_continue_vip).setLayoutParams(lps);
//                mMaskLayout.findViewById(R.id.rip_ll_watch_ad).setVisibility(View.VISIBLE);
//                if (mBluredScreenBitmap == null) {
//                    createBluredScreenBitmap();
//                }
//                mMaskLayout.setBackground(new BitmapDrawable(mBluredScreenBitmap));
////                StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_VIDEO_BUTTON_SHOW,
////                        StatisticsConstant.KEY_SHOW_TYPE, StatisticsConstant.VALUE_BUTTON,
////                        StatisticsConstant.KEY_VIP_FUN, StatisticsConstant.VALUE_RATE_TIME_GENDER_SWAP);
        }
    }

    private void startRequest() {
        mIsLoading = true;
    }

    private void stopRequest() {
        mIsLoading = false;
    }

    public boolean isLoading() {
        return mIsLoading;
    }

    /**
     * 获取接口请求的耗时区间
     *
     * @param startRequest 开始请求时间
     * @return 区间文本
     */
    private String getTimeInterval(long startRequest) {
        long successRequest = System.currentTimeMillis();
        long diff = successRequest - startRequest;
        float second = diff / 1000f;
        String secondText = "";
        if (second < 4) {
            secondText = "[0.4)";
        } else if (second >= 4 && second < 6) {
            secondText = "[4.6)";
        } else if (second >= 6 && second < 10) {
            secondText = "[6.10)";
        } else if (second >= 10) {
            secondText = "[10.)";
        }
        return secondText;
    }

    /**
     * 换脸接口成功，统计耗时区间
     *
     * @param second 耗时区间
     */
    private void requestSucceedStat(String second) {
//        StatisticsUtils.statisicsCustomFunction(UMENG_CUSTOM_EVENT_EDITOR, UMENG_CUSTOM_KEY_FUNCTION,
//                StatisticsConstant.UMENG_CUSTOM_EVENT_FUNC_MAINPAGE +
//                        StatisticsConstant.UMENG_CUSTOM_UNDER_LINE +
//                        StatisticsConstant.MAIN_BTN_SWAP +
//                        StatisticsConstant.UMENG_CUSTOM_UNDER_LINE +
//                        StatisticsConstant.FACE_SWAP_REQUEST_SUCCESS +
//                        StatisticsConstant.UMENG_CUSTOM_UNDER_LINE +
//                        second
//        );
    }

    private void requestBabyReport(BabyInputBean inputBean) {
        showLoading();
        final long startTime = System.currentTimeMillis();
        JSONObject postData = new JSONObject();
        try {
            postData.put("key", "any");
            postData.put("ethnicity", inputBean.getItemId());
            postData.put("sex", inputBean.getBabySex());
            SignUtils.appendSign(postData);
            OkGo.<BabyPredicResultBean>post(FaceUtil.BASE_URL + FaceUtil.METHOD_BABY)
                    .tag(this)
                    .retryCount(1)
                    .cacheMode(CacheMode.NO_CACHE)
                    .upJson(postData)
                    .execute(new JsonCallback<BabyPredicResultBean>() {
                        @Override
                        public void onStart(Request<BabyPredicResultBean, ? extends Request> request) {

                        }

                        @Override
                        public void onSuccess(Response<BabyPredicResultBean> response) {
                            statisticsRequestSuccess(startTime);

                            hideLoading();
                            BabyPredicResultBean babyPredicResultBean = null;
                            if (response != null) {
                                babyPredicResultBean = response.body();
                                if (babyPredicResultBean != null && babyPredicResultBean.isSuccess() && babyPredicResultBean.getData() != null) {
                                    handleResult(babyPredicResultBean);
                                    return;
                                }
                            }
//                            long currentTimeMillis = System.currentTimeMillis();
//                            long interval = currentTimeMillis - startTime;
//                            String requTime = "";
//                            if (interval < 4 * 1000) {
//                                requTime = "(0,4)";
//                            } else if (interval < 6 * 1000) {
//                                requTime = "(4,6)";
//                            } else if (interval < 10 * 1000) {
//                                requTime = "(6,10)";
//                            } else {
//                                requTime = "(10,)";
//                            }
//                            StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_SCAN_REQ_SUCCESS,
//                                    StatisticsConstant.PROPERTY_KEY_IF_SUB, AppVipManager.isVip() ? StatisticsConstant.PROPERTY_VALUE_SUB : StatisticsConstant.PROPERTY_VALUE_UNSUB,
//                                    StatisticsConstant.KEY_TREND_FUN, StatisticsConstant.VALUE_RATE_TIME_FUTURE_BABY,
//                                    StatisticsConstant.KEY_PIC_SOURCE, "album",
//                                    StatisticsConstant.KEY_REQ_TIME, requTime);
                            if (babyPredicResultBean != null) {
                                DLog.d(TAG, babyPredicResultBean.getMessage());
                            }
                        }


                        @Override
                        public void onError(Response<BabyPredicResultBean> response) {
                            hideLoading();
                            ToastUtil.showToast(mActivity.getString(R.string.net_connect_error));

                            StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_SCAN_REQ_FAIL,
                                    StatisticsConstant.PROPERTY_KEY_IF_SUB, AppVipManager.isVip() ? StatisticsConstant.PROPERTY_VALUE_SUB : StatisticsConstant.PROPERTY_VALUE_UNSUB,
                                    StatisticsConstant.KEY_TREND_FUN, StatisticsConstant.VALUE_RATE_TIME_FUTURE_BABY,
                                    StatisticsConstant.KEY_PIC_SOURCE, ((FaceLogicActivity)mContext).getPicSource(),
                                    StatisticsConstant.KEY_REQUEST_FAILED_REASON, response.message());

                            //失败2次设置默认图像
                            int count = SpUtils.obtain().getInt("requestBaby", 0);
                            if (count < 1) {
                                SpUtils.obtain().save("requestBaby", count+1);
                            }else {
                                SpUtils.obtain().save("requestBaby", 0);
                                mImgResult.setImageResource(R.drawable.ic_baby_model);
                            }
                        }


                        @Override
                        public void onFinish() {

                        }
                    });
        } catch (JSONException e) {
            e.printStackTrace();
            ToastUtil.showToast(mActivity.getString(R.string.net_connect_error));
        }
    }

    private void statisticsRequestSuccess(long startTime) {
        long currentTimeMillis = System.currentTimeMillis();
        long interval = currentTimeMillis - startTime;
        String requTime = "";
        if (interval < 4 * 1000) {
            requTime = "(0,4)";
        } else if (interval < 6 * 1000) {
            requTime = "(4,6)";
        } else if (interval < 10 * 1000) {
            requTime = "(6,10)";
        } else {
            requTime = "(10,)";
        }
        StatisticsUtils.statisticGrowingIo(StatisticsConstant.EVENT_SCAN_REQ_SUCCESS,
                StatisticsConstant.PROPERTY_KEY_IF_SUB, AppVipManager.isVip() ? StatisticsConstant.PROPERTY_VALUE_SUB : StatisticsConstant.PROPERTY_VALUE_UNSUB,
                StatisticsConstant.KEY_TREND_FUN, StatisticsConstant.VALUE_RATE_TIME_FUTURE_BABY,
                StatisticsConstant.KEY_PIC_SOURCE, ((FaceLogicActivity)mContext).getPicSource(),
                StatisticsConstant.KEY_REQ_TIME, requTime);
    }

    private void handleResult(final BabyPredicResultBean babyPredicResultBean) {
        ThreadPool.runOnNonUIThread(new Runnable() {
            @Override
            public void run() {
                babyPredicResultBean.setPic(babyPredicResultBean.getData().getPic());
                babyPredicResultBean.getData().setPic("");
                mCurrentPath = babyPredicResultBean.getPic();

                Bitmap bitmap = BitmapUtils.base64ToBitmap(mCurrentPath);

                ThreadPool.runUITask(new Runnable() {
                    @Override
                    public void run() {
                        mImgResult.setImageBitmap(bitmap);
                    }
                });
            }
        });
    }

    private long startRequest;

    protected String getStatisticsSuccessType() {
        if (startRequest == 0) {
            startRequest = System.currentTimeMillis();
        }
        long durationSec = (System.currentTimeMillis() - startRequest) / TimeConstant.ONE_SEC;
        if (durationSec <= 4 && durationSec >= 0) {
            return STATISTIC_EVENT_VALUE_FACE_AGING_PARKING_TIME_4;
        } else if (durationSec <= 6) {
            return STATISTIC_EVENT_VALUE_FACE_AGING_PARKING_TIME_6;
        } else if (durationSec <= 10) {
            return STATISTIC_EVENT_VALUE_FACE_AGING_PARKING_TIME_10;
        } else {
            return STATISTIC_EVENT_VALUE_FACE_AGING_PARKING_TIME_ABOVE_10;
        }
    }

    private void statisFaild() {
        StatisticsUtils.statisticsFaceSecret(StatisticsConstant.STATISTIC_EVENT_FUN_VALUE_GENDER_SWITCH + "_" +
                StatisticsConstant.STATISTIC_EVENT_VALUE_REPORT_GET_PIC_FAIL + "_"
                + StatisticsConstant.STATISTIC_EVENT_VALUE_REQUEST);
    }

    @Override
    public Bitmap getSaveImg() {
        if (mIsModel) {
            return APKAssertImageLoader.with(mContext.getResources()).load(mCurrentPath).get();
        }
        if (!TextUtils.isEmpty(mCurrentPath)) {
            Bitmap bitmap = BitmapUtils.base64ToBitmap(mCurrentPath);
            if (bitmap == null) {
                bitmap = ImageHelper.getBitmapFromPath(mCurrentPath);
            }
            return bitmap;
        } else {
            return ImageHelper.getBitmapFromPath(mImagePath);
        }
    }

    private void showLoading() {
        if (mLoadingView != null) {
            mLoadingView.setVisibility(View.VISIBLE);
            mLoadingView.playAnimation();
            mIsLoading = true;
            if (mActivity instanceof FaceLogicActivity) {
                ((FaceLogicActivity) mActivity).getEmptyView().setVisibility(View.VISIBLE);
            }
        }
    }

    private void hideLoading() {
        if (mLoadingView != null) {
            mLoadingView.setVisibility(View.GONE);
            mLoadingView.cancelAnimation();
            mIsLoading = false;
            if (mActivity instanceof FaceLogicActivity) {
                ((FaceLogicActivity) mActivity).getEmptyView().setVisibility(View.GONE);
            }
        }
    }

    /**
     * 显示最终图片的同时，需要更换模糊背景，更换模糊背景genBackground，直接rx子线程执行。
     *
     * @param pic
     */
    private void showSwapPic(final String pic) {
        ThreadPool.runUITask(new Runnable() {
            @Override
            public void run() {
                ImageLoader.loadImageFromBase64(ComponentContext.getContext(), pic, mImgResult);
                mCurrentPath = pic;
            }
        });
    }

    @Override
    public int getReportTitleResId() {
        return R.string.future_baby;
    }

    @Override
    public String getFeatureType() {
        return StatisticsConstant.STATISTIC_EVENT_FEATURE_VALUE_FEATURE_FUTURE_BABY;
    }

    @Override
    public boolean needScrool() {
        return true;
    }


    @Override
    public boolean titleBarWithoutBg() {
        return true;
    }

    public void destroy() {
        mActivity = null;
        OkGo.getInstance().cancelTag(this);
    }

}
